package com.zboin.common.utils;

import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * @author zhboom
 * @date 2025/7/21 22:05
 */
public class JwtUtils {

    private static final String SECRET_STRING = "qwer1234asdf5678zxvc0147jiangakskkkgajsodi165967911363";
    private static final Key SECRET_KEY = new SecretKeySpec(SECRET_STRING.getBytes(), SignatureAlgorithm.HS256.getJcaName());
    private static final long EXPIRATION = 1800000; // 30 minutes

    public static String generateToken(String userId) {
        long now = System.currentTimeMillis();
        String jwtId = UUID.randomUUID().toString();
        return Jwts.builder()
                .setId(jwtId)
                .setIssuedAt(new Date(now))
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .setSubject(userId)
                .signWith(SECRET_KEY)
                .compact();
    }

    public static String generateToken(String userId, Map<String, Object> claims) {
        long now = System.currentTimeMillis();
        String jwtId = UUID.randomUUID().toString();
        return Jwts.builder()
                .setId(jwtId)
                .setIssuedAt(new Date(now))
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .setSubject(userId)
                .setClaims(claims)
                .signWith(SECRET_KEY)
                .compact();
    }

    public static String getUserIdFromToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(SECRET_KEY)
                .build()
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
    }

    public static boolean validateToken(String token) {
        try {
            Jwts.parserBuilder()
                    .setSigningKey(SECRET_KEY)
                    .build()
                    .parseClaimsJws(token);
            return true;
        } catch (JwtException e) {
            return false;
        }
    }
}
